//
//  PlanDetailViewController.m
//  SportSocial
//
//  Created by yull on 15/1/14.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "PlanDetailViewController.h"
#import "PlanSelectPanelView.h"

#import "PlanFirstReusableView.h"
#import "PlanSecondReusableView.h"

#import "PlanRunCell.h"
#import "PhotoCell.h"
#import "PlanOtherCell.h"

#import "PlanInfo.h"
#import "PhotoNet.h"

#import "PlanDao.h"
#import "RunInfoDao.h"
#import "RunInfo.h"
#import "TimeSelectView.h"

#import "PlanRunViewController.h"
#import "PlanAddView.h"

#import "SportPlanNet.h"
#import "LocationManager.h"
#import "ShareNet.h"
#import "UIImage+resize.h"

#import <ShareSDK/ShareSDK.h>

@interface PlanDetailViewController() <UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,PlanRunCellDelegate,PlanOtherCellDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,TimeSelectViewDelegate,PlanAddViewDelegate>

@property (nonatomic, strong) UICollectionView *planCollectionView;

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIImageView *progressImageView;
@property (nonatomic, strong) UIView *sportSelectView;

@property (nonatomic, strong) UIView *panelView;
@property (nonatomic, strong) UIView *blackView;
@property (nonatomic, strong) PlanAddView *addView;

@property (nonatomic, strong) PlanOtherCell *selectCell;
@property (nonatomic, strong) TimeSelectView *selectView;

@property (nonatomic, strong) NSMutableArray *photoArray;

@property (nonatomic, strong) NSString *shareUrl;
@end

@implementation PlanDetailViewController

-(void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initNavibar];
    
    [self initTableView];
    
    [self initSelectView];
    
    [self initPlanAddView];
    
    [self loadPhoto];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.planCollectionView reloadData];
}

- (void)initNavibar
{
    [self addCommonBackButton];
    
    UIButton *rightButton1 = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton1.frame = CGRectMake(0, 0, 85, 26);
    [rightButton1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightButton1 setTitle:@"添加运动计划" forState:UIControlStateNormal];
    rightButton1.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [rightButton1 addTarget:self action:@selector(onClickAddPlan:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem1 = [[UIBarButtonItem alloc] initWithCustomView:rightButton1];
    self.navigationItem.rightBarButtonItem = rightItem1;
}

- (void)initPlanAddView
{
    CGRect rect = self.navigationController.view.bounds;
    
    self.panelView = [[UIView alloc] initWithFrame:rect];
    [self.navigationController.view addSubview:self.panelView];
    
    self.blackView = [[UIView alloc] initWithFrame:self.panelView.bounds];
    self.blackView.backgroundColor = [UIColor blackColor];
    self.blackView.alpha = 0.3f;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapGesture:)];
    [self.blackView addGestureRecognizer:tap];
    [self.panelView addSubview:self.blackView];
    
    rect = CGRectMake(10, 0, self.view.width - 20, 0);
    self.addView = [[PlanAddView alloc] initWithFrame:rect];
    self.addView.delegate = self;
    self.addView.centerX = self.panelView.width/2;
    self.addView.centerY = self.panelView.height/2;
    [self.panelView addSubview:self.addView];
    
    self.panelView.hidden = YES;
    self.addView.hidden = YES;
    self.blackView.hidden = YES;
}

- (void)initSelectView
{
    self.selectView = [[TimeSelectView alloc] initWithFrame:CGRectMake(0, self.view.height, self.view.width, 256)];
    self.selectView.delegate = self;
    [self.view addSubview:self.selectView];
}

- (void)initTableView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.sectionInset = UIEdgeInsetsZero;
    
    CGRect rect = CGRectMake(0, 0, self.view.width, self.view.height);
    self.planCollectionView = [[UICollectionView alloc] initWithFrame:rect collectionViewLayout:flowLayout];
    self.planCollectionView.delegate = self;
    self.planCollectionView.dataSource = self;
    self.planCollectionView.backgroundColor = [UIColor clearColor];
    
    [self.planCollectionView registerClass:[PlanFirstReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"FirstSection"];
    [self.planCollectionView registerClass:[PlanSecondReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SecondSection"];
    
    [self.planCollectionView registerClass:[PlanRunCell class] forCellWithReuseIdentifier:@"PlanRunCell"];
    [self.planCollectionView registerClass:[PlanOtherCell class] forCellWithReuseIdentifier:@"PlanOtherCell"];
    [self.planCollectionView registerClass:[PhotoCell class] forCellWithReuseIdentifier:@"PhotoCell"];
    
    [self.view addSubview:self.planCollectionView];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.planArray.count;
    }else {
        return self.photoArray.count;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return CGSizeMake(collectionView.width, 100);
    }else {
        CGFloat width = (SCREEN_WIDTH - 40) / 3;
        return CGSizeMake(width, width);
    }
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }
    return 5;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }
    return 5;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if (section == 0) {
        return UIEdgeInsetsMake(0, 0, 10, 0);
    }
    return UIEdgeInsetsMake(0, 15, 15, 15);
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        PlanInfo *planInfo = [self.planArray objectAtIndex:indexPath.row];
        if ([planInfo.sport_name isEqualToString:@"跑步"]) {
            PlanRunCell *planCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PlanRunCell" forIndexPath:indexPath];
            planCell.delegate = self;
            [planCell drawCellWithPlanInfo:planInfo];
            return planCell;
        }else{
            PlanOtherCell *planCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PlanOtherCell" forIndexPath:indexPath];
            [planCell drawCellWithPlanInfo:planInfo];
            planCell.delegate = self;
            return planCell;
        }
    }else {
        PhotoCell *photoCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PhotoCell" forIndexPath:indexPath];
        [photoCell drawCellWithUrl:@"http://img0.bdstatic.com/img/image/6446027056db8afa73b23eaf953dadde1410240902.jpg"];
        return photoCell;
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        PlanFirstReusableView *firstSectionView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"FirstSection" forIndexPath:indexPath];
        [firstSectionView drawCellWithProgress:[self getFinishedPercent]];
        return firstSectionView;
    }else {
        PlanSecondReusableView *secondSectionView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"SecondSection" forIndexPath:indexPath];
        return secondSectionView;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return CGSizeMake(collectionView.width, 50);
    }else {
        return CGSizeMake(collectionView.width, 30);
    }
}

#pragma mark - PlanRunCellDelegate,PlanOtherCellDelegate

- (void)takePhotoWithPlanInfo:(PlanInfo *)planInfo
{
    BOOL rearCameraAvailable = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];//前
    BOOL frontCameraAvailable = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
    
    if (!rearCameraAvailable && !frontCameraAvailable) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"此设备相机不可用" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    NSUInteger sourceType = 0;//初始化调用相机相册的方法
    sourceType = UIImagePickerControllerSourceTypeCamera;//调用相册
    
    UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourceType;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

- (void)shareWithPlanInfo:(PlanInfo *)planInfo
{
    NSLog(@"分享");
    
    [self showText:@"上传图片中..."];
    [ShareNet shareWithImage:UIImageJPEGRepresentation([self takeScreentShot], 0.3) successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self hideHUD];
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            self.shareUrl = [responseObject objectForKey:@"data"];
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self sharePlan:planInfo];
            });
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hideHUD];
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)sharePlan:(PlanInfo *)planInfo
{
    //构造分享内容
    NSString *content = [NSString stringWithFormat:@"我今天运动了%f秒，消耗了%ld大卡，快来看看吧", planInfo.end_date-planInfo.start_date, (long)planInfo.calorie];
    
    id<ISSContent> publishContent = [ShareSDK content:content
                                       defaultContent:planInfo.sport_name
                                                image:[ShareSDK pngImageWithImage:[[self takeScreentShot] reSizeImageToSize:CGSizeMake(self.view.width/6, self.view.height/6)]]
                                                title:planInfo.sport_name
                                                  url:self.shareUrl
                                          description:content
                                            mediaType:SSPublishContentMediaTypeNews];
    //创建弹出菜单容器
    id<ISSContainer> container = [ShareSDK container];
    
    NSMutableArray *shareList = [NSMutableArray arrayWithArray:[ShareSDK getShareListWithType:ShareTypeSinaWeibo,ShareTypeQQ,ShareTypeWeixiSession,ShareTypeWeixiTimeline, nil]];
    if (![QQApi isQQInstalled] || ![QQApi isQQSupportApi]) {
        [shareList removeObject:@(24)];
    }
    if (![WXApi isWXAppInstalled] || ![WXApi isWXAppSupportApi]) {
        [shareList removeObject:@(22)];
        [shareList removeObject:@(23)];
    }
    
    //弹出分享菜单
    [ShareSDK showShareActionSheet:container
                         shareList:shareList
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions:nil
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                
                                if (state == SSResponseStateSuccess)
                                {
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_SUC", @"分享成功"));
                                }
                                else if (state == SSResponseStateFail)
                                {
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        [self showText:[NSString stringWithFormat:@"%@", [error errorDescription]]];
                                    });
                                    
                                    NSLog(NSLocalizedString(@"TEXT_ShARE_FAI", @"分享失败,错误码:%d,错误描述:%@"), [error errorCode], [error errorDescription]);
                                }
                            }];
}

- (void)deleteInfo:(PlanInfo *)planInfo
{
    if (self.deletePlanInfo) {
        self.deletePlanInfo(planInfo);
    }
    
    [[PlanDao shareInstance] deletePlanInfo:planInfo];
    
    [self.planArray removeObject:planInfo];
    
    [self.planCollectionView reloadData];
}

- (void)runWithPlanInfo:(PlanInfo *)planInfo
{
    PlanRunViewController *planRun = [[PlanRunViewController alloc] init];
    planRun.planInfo = planInfo;
    [self.navigationController pushViewController:planRun animated:YES];
}

- (void)selectTimeInCell:(PlanOtherCell *)otherCell
{
    self.selectCell = otherCell;
    [self showSelectView];
}

- (void)onClickAddPlan:(id)sender
{
    if (self.planArray.count >= 3) {
        [self showText:@"最多只能添加3个运动"];
        return;
    }
    
    self.blackView.alpha = 0.0f;
    self.addView.alpha = 0.0f;
    self.blackView.hidden = NO;
    self.addView.hidden = NO;
    self.panelView.hidden = NO;
    [UIView animateWithDuration:0.3f animations:^{
        self.blackView.alpha = 0.3f;
        self.addView.alpha = 1.0f;
    }];
}

- (void)onTapGesture:(id)gesture
{
    [UIView animateWithDuration:0.3f animations:^{
        self.blackView.alpha = 0.0f;
        self.addView.alpha = 0.0f;
    } completion:^(BOOL finished) {
        self.blackView.hidden = YES;
        self.addView.hidden = YES;
        self.panelView.hidden = YES;
    }];
}
#pragma mark - 拍照
//点击use调用的方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //要上传的图片
    UIImage *photoImage = [info objectForKey:UIImagePickerControllerEditedImage];
    
    [self uploadImage:photoImage];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)uploadImage:(UIImage *)image
{
    [self showHUD];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.3f);
    [PhotoNet uploadPhotoData:imageData successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self hideHUD];
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:@"上传成功！" time:2];
            });
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hideHUD];
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

#pragma mark - TimeSelectViewDelegate
- (void)onCancel
{
    [self hideSelectView];
}

- (void)onConfirmWithDate:(NSDate *)date
{
    [self hideSelectView];
    
    if (self.selectCell) {
        PlanInfo *planInfo = self.selectCell.planInfo;
        
        planInfo.end_date = [date timeIntervalSince1970];
        
        if (planInfo.end_date < planInfo.start_date) {
            planInfo.end_date = planInfo.start_date;
        }
        
        planInfo.calorie = [self.selectCell calculateCalorie];
        
        [self updatePlanInfo:planInfo];
        
        [self.selectCell drawCellWithPlanInfo:planInfo];
    }
}

- (void)hideSelectView
{
    [UIView animateWithDuration:0.3f animations:^{
        self.selectView.top = self.view.height;
    }];
}

- (void)showSelectView
{
    CGFloat orginy = self.view.height - self.selectView.height;
    
    self.selectView.picker.minimumDate = [NSDate dateWithTimeIntervalSince1970:self.selectCell.planInfo.start_date];
    
    [UIView animateWithDuration:0.3f animations:^{
        self.selectView.top = orginy;
    }];
}

- (void)selectSportName:(NSString *)name imageName:(NSString *)imageName
{
    NSLog(@"%@ %@",name,imageName);
    PlanInfo *planInfo = [[PlanInfo alloc] init];
    planInfo.sport_name = name;
    planInfo.icon = imageName;
    planInfo.day = self.day;
    planInfo.month = self.month;
    planInfo.year = self.year;
    
    [self.planArray addObject:planInfo];
    
    [self.planCollectionView reloadData];
    
    if (self.addPlanInfo) {
        self.addPlanInfo(planInfo);
    }
    
    [self onTapGesture:nil];
}

#pragma mark - 更新运动计划
- (void)updatePlanInfo:(PlanInfo *)planInfo
{
    if ([[PlanDao shareInstance] updatePlanInfo:planInfo]) {
        NSLog(@"运动计划更新成功!");
    }else {
        NSLog(@"运动计划更新失败!");
    }
    
    if (planInfo.status == PlanInfoStatusEnd) {
    
        [self.planCollectionView reloadData];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PlanInfoStatusChange" object:nil];
        
        if ([planInfo.sport_name isEqualToString:@"跑步"]) {
            
            [self showHUD];
            
            if (!planInfo.locations) {
                NSArray *locations = [[RunInfoDao shareInstance] selectRunInfoWithPlanId:planInfo.dbId];
                planInfo.locations = [NSMutableArray arrayWithArray:locations];
            }
            
            if (planInfo.max_speed <= 0 || planInfo.avg_speed <= 0) {
                
                double totalSpeed = 0;
                for (RunInfo *runInfo in planInfo.locations) {
                    planInfo.max_speed =MAX(planInfo.max_speed, runInfo.speed);
                    totalSpeed += runInfo.speed;
                }
                
                planInfo.avg_speed = totalSpeed / (planInfo.locations.count);
            }
            
            [SportPlanNet uploadHistoryWithSportName:@"跑步"
                                           startDate:[planInfo convertStartDateToString]
                                             endDate:[planInfo convertEndDateToString]
                                           longitude:[LocationManager shareInstance].location.coordinate.longitude
                                            latitude:[LocationManager shareInstance].location.coordinate.latitude
                                             calorie:planInfo.calorie
                                            distance:planInfo.distance
                                            maxSpeed:planInfo.max_speed
                                            avgSpeed:planInfo.avg_speed
                                           locations:[self convertLocationsToJson:planInfo]
                                        successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
                                            [self hideHUD];
                                            
                                            BOOL success = [[responseObject objectForKey:@"success"] boolValue];
                                            if (success) {
                                                dispatch_async(dispatch_get_main_queue(), ^{
                                                    [self showText:@"上传成功！" time:2];
                                                });
                                            } else {
                                                NSString *message = [responseObject objectForKey:@"message"];
                                                
                                                dispatch_async(dispatch_get_main_queue(), ^{
                                                    [self showText:message time:2];
                                                });
                                            }
                                        } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
                                            [self hideHUD];
                                            
                                            dispatch_async(dispatch_get_main_queue(), ^{
                                                [self showText:@"网络连接失败" time:2];
                                            });
                                        }];
            
        } else {
            [self showHUD];
            
            [SportPlanNet uploadHistoryWithSportName:planInfo.sport_name
                                           startDate:[planInfo convertStartDateToString]
                                             endDate:[planInfo convertEndDateToString]
                                           longitude:[LocationManager shareInstance].location.coordinate.longitude
                                            latitude:[LocationManager shareInstance].location.coordinate.latitude
                                             calorie:planInfo.calorie
                                        successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
                                            
                                            [self hideHUD];
                                            
                                            BOOL success = [[responseObject objectForKey:@"success"] boolValue];
                                            if (success) {
                                                dispatch_async(dispatch_get_main_queue(), ^{
                                                    [self showText:@"上传成功！" time:2];
                                                });
                                            } else {
                                                NSString *message = [responseObject objectForKey:@"message"];
                                                
                                                dispatch_async(dispatch_get_main_queue(), ^{
                                                    [self showText:message time:2];
                                                });
                                            }
                                           } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
                                               [self hideHUD];
                                               
                                               dispatch_async(dispatch_get_main_queue(), ^{
                                                   [self showText:@"网络连接失败" time:2];
                                               });
                                           }];
        }
    }
}

- (NSArray *)convertLocationsToJson:(PlanInfo *)planInfo
{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    
    NSMutableArray *locations = [NSMutableArray array];
    for (RunInfo *runInfo in planInfo.locations) {
        @autoreleasepool {
            NSDictionary *locationDic = @{@"locate_date":[dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:runInfo.locate_date]],
                                          @"altitude":@(runInfo.altitude),
                                          @"longitude":@(runInfo.longitude),
                                          @"latitude":@(runInfo.latitude),
                                          @"speed":@(runInfo.speed),
                                          @"bearing":@(runInfo.bearing),
                                          @"accuracy":@([BMKLocationService getCurrentLocationDesiredAccuracy])};
            [locations addObject:locationDic];
        }
    }
    
    return locations;
    /*
    NSData *data = [NSJSONSerialization dataWithJSONObject:locations options:NSJSONWritingPrettyPrinted error:nil];
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
     */
}

#pragma mark - 相册
- (void)loadPhoto
{
    NSString *from_date = [[NSString alloc] initWithFormat:@"%02d-%02d-%02d",self.year,self.month,self.day];
    NSString *to_date = [[NSString alloc] initWithFormat:@"%02d-%02d-%02d",self.year,self.month,self.day+1];
    [PhotoNet queryByFromDate:from_date toDate:to_date successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (NSInteger) getFinishedPercent
{
    if (self.planArray.count == 0) {
        return 0;
    }
    
    NSInteger finishedCount = 0;
    for (PlanInfo *planInfo in self.planArray) {
        if (planInfo.status == PlanInfoStatusEnd) {
            finishedCount ++;
        }
    }
    
    return (NSInteger)(finishedCount * 1.0/self.planArray.count *100);
}

#pragma mark - 屏幕截图
- (UIImage *)takeScreentShot
{
    UIWindow *screenWindow = [[UIApplication sharedApplication] keyWindow];
    UIGraphicsBeginImageContext(screenWindow.frame.size);
    [screenWindow.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return viewImage;
}
@end
